import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { UserInterface, UserUpdateInterface, BindPhoneInterface, BindWechatCodeInterface } from './interfaces/user.interfaces';
import { serviceInfoLog } from "src/common/out/logger/access.logger";
import { VirtualCharacter } from '../virtual-character/virtual-character.entity';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private userRepository: Repository<User>,
        @InjectRepository(VirtualCharacter)
        private virtualCharacterRepository: Repository<VirtualCharacter>,
    ) { }

    createUser(user: UserInterface) {
        return this.userRepository.save(user);
    }

    async findUser(userid: string) {
        const user = await this.userRepository.findOne({ where: { userid } });
        if (!user) {
            return null;
        }

        const virtualCharacter = await this.virtualCharacterRepository.findOne({
            where: { 
                userId: userid,
                isActive: true 
            },
            order: {
                updateTime: 'DESC'
            }
        });

        return {
            ...user,
            virtualCharacter: virtualCharacter || null
        };
    }

    async updateUser(userUpdate: UserUpdateInterface) {
        const { nickName, avatar } = userUpdate
        return this.userRepository.update({ userid: userUpdate.userid }, { nickName, avatar });
    }

    findUserByPhone(phone: string) {
        serviceInfoLog(`findUserByPhone ${phone}`)
        return this.userRepository.findOne({ where: { phone } });
    }

    async bindWechatCode(bindWechatCode: BindWechatCodeInterface) {
        serviceInfoLog(`bindWechatCode ${bindWechatCode}`)
        const { wechatCode } = bindWechatCode
        return this.userRepository.update({ userid: bindWechatCode.userid }, { wechatCode });
    }

    async bindPhone(bindPhone: BindPhoneInterface) {
        serviceInfoLog(`bindWechatCode ${bindPhone}`)
        const { phone } = bindPhone
        return this.userRepository.update({ userid: bindPhone.userid }, { phone });
    }

    async updateVirtualCharacterInfo(userId: string, virtualCharacterId: string) {
        return this.userRepository.update(
            { userid: userId },
            { 
                hasVirtualCharacter: true,
                virtualCharacterId: virtualCharacterId
            }
        );
    }
}
